# Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes <%= fetch(:mb_unicorn_workers) %>

# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
working_directory "<%= current_path %>"

# listen on both a Unix domain socket
# we use a shorter backlog for quicker failover when busy
listen "/tmp/unicorn.<%= application_basename %>.sock", :backlog => 64

# nuke workers after <%= fetch(:mb_unicorn_timeout) %> seconds (default is 60)
timeout <%= fetch(:mb_unicorn_timeout) %>

pid "<%= fetch(:mb_unicorn_pid) %>"

# By default, the Unicorn logger will write to stderr.
# Additionally, some applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
stderr_path "<%= fetch(:mb_unicorn_log) %>"
stdout_path "<%= fetch(:mb_unicorn_log) %>"

preload_app true

# combine Ruby 2.0.0dev or REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
if GC.respond_to?(:copy_on_write_friendly=)
  GC.copy_on_write_friendly = true
end

before_exec do |server|
  # Ensure unicorn picks up our newest Gemfile
  ENV['BUNDLE_GEMFILE'] = "<%= current_path %>/Gemfile"
end

before_fork do |server, worker|

  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  if defined? ActiveRecord::Base
    ActiveRecord::Base.connection.disconnect!
  end

  # This allows a new master process to incrementally
  # phase out the old master process with SIGTTOU to avoid a
  # thundering herd (especially in the "preload_app false" case)
  # when doing a transparent upgrade.  The last worker spawned
  # will then kill off the old master process with a SIGQUIT.
  old_pid = "#{server.config[:pid]}.oldbin"
  if File.exists?(old_pid) && server.pid != old_pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end

  # Throttle the master from forking too quickly by sleeping.  Due
  # to the implementation of standard Unix signal handlers, this
  # helps (but does not completely) prevent identical, repeated signals
  # from being lost when the receiving process is busy.
  sleep 1
end

after_fork do |server, worker|
  # the following is *required* for Rails + "preload_app true"
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
  end
end
